package Redis.sds;

import java.nio.charset.StandardCharsets;
import java.util.Arrays;

/**
 * @author welsir
 * @version 1.0
 * @description: TODO
 * @date 2022/10/2 14:17
 */
public class SDS {
    int len;
    int free;
    char buf[];

    public SDS(String msg){
        buf = msg.toCharArray();
        len = msg.length();
        free = 0;
    }

    public static void printBuf(SDS sds){
        System.out.println(" len is "+sds.len);
        System.out.println(" free is "+sds.free);
        System.out.println(" buf is "+Arrays.toString(sds.buf));
    }

    public void append(SDS oldSDS,String appendText){
//        如果剩余空间长度大于追加长度
        if(oldSDS.free>=appendText.length()){
            System.arraycopy(appendText.toCharArray(),0,oldSDS.buf,oldSDS.len,appendText.length());
            oldSDS.free -= appendText.length();
            oldSDS.len+=appendText.length();
        }else {
//            否则判断空间大小是否满足1MB条件
            byte[] bytes = Arrays.toString(oldSDS.buf).getBytes(StandardCharsets.UTF_8);
            if(bytes.length>=1024*1024){
//                如果内存大小满足条件,在原拼接后内存大小上在加上一个1MB大小
                char[] newBuf = new char[1024*1024+oldSDS.buf.length+appendText.length()];
                oldSDS.len+=appendText.length();
                free = newBuf.length-len;
                System.arraycopy(oldSDS.buf,0,newBuf,0,oldSDS.len);
                System.arraycopy(appendText.toCharArray(),0,newBuf,oldSDS.len,appendText.length());
                oldSDS.buf=newBuf;
            }else {
//                如果不满足条件，在追加后内存大小基础上翻倍
                int newLen = oldSDS.len+appendText.length();
                char[] newBuf = new char[newLen*2];
                System.arraycopy(oldSDS.buf,0,newBuf,0,oldSDS.len);
                System.arraycopy(appendText.toCharArray(),0,newBuf,oldSDS.len,appendText.length());
                oldSDS.buf=newBuf;
                oldSDS.len = newLen;
                oldSDS.free = newLen*2-oldSDS.len;
            }
        }
    }

    public int getLen() {
        return len;
    }

    public void setLen(int len) {
        this.len = len;
    }

    public int getFree() {
        return free;
    }

    public void setFree(int free) {
        this.free = free;
    }

    public char[] getBuf() {
        return buf;
    }

    public void setBuf(char[] buf) {
        this.buf = buf;
    }

}
